#include "head.h"

int make_child(processData_t* workerList,int childNum)
{
    int i;
    pid_t pid;
    int pipefds[2];//管道
    for(i=0;i<childNum;i++)
    {
        socketpair(AF_LOCAL,SOCK_STREAM,0,pipefds);//初始化tcp类型管道
        pid=fork();
        if(0==pid)
        {
            close(pipefds[1]);//子进程关闭其中一端
            handleEvent(pipefds[0]);
        }
        //父进程才会走到这里,保存子进程pid，初始化子进程状态
        close(pipefds[0]);//父进程关闭其中一端
        workerList[i].pid=pid;
        workerList[i].status=FREE;
        workerList[i].pipeFd=pipefds[1];
#ifdef DEBUG
        printf("workerList[%d].pipeFd=%d\n",i,workerList[i].pipeFd);
#endif
    }
    return 0;
}

int handleEvent(int pipeFd)
{
    int new_fd,finish_flag=1;
    while(1)
    {
        //接受任务
        recvFd(pipeFd,&new_fd);
        printf("recv parent task %d\n",new_fd);
        //给客户端发送文件
        transFile(new_fd);
        close(new_fd);
        //通知父进程完成任务
        write(pipeFd,&finish_flag,sizeof(int));
    }
}